package com.weayer.service;

import com.weayer.dto.ResponseResult;
import com.weayer.dto.Car;
import com.weayer.mapper.CarMapper;
import com.weayer.remote.ServiceMapClient;
import com.weayer.response.AddTerminalResponse;
import com.weayer.response.TrackResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 车辆管理Service
 * @author: Weayer
 **/
@Service
public class CarService {
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private ServiceMapClient serviceMapClient;

    /**
     * @Description: 添加车辆信息
     * @Param: [car]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult addCar(Car car){
        // 1. 添加到车辆信息，根据车辆名称、id创建车辆终端
        LocalDateTime now = LocalDateTime.now();
        car.setGmtCreate(now);
        car.setGmtModified(now);
        carMapper.insert(car);
        AddTerminalResponse terminalResponse = serviceMapClient.addTerminal(car.getVehicleNo(), car.getId()+"").getData();
        // 2. 获取终端tid，创建轨迹到终端
        String tid = terminalResponse.getTid();
        car.setTid(tid);
        TrackResponse trackResponse = serviceMapClient.addTrack(tid).getData();
        // 3. 获取轨迹trid，更新车辆信息
        car.setTrid(trackResponse.getTrid());
        car.setTrname(trackResponse.getTrname());
        carMapper.updateById(car);
        return ResponseResult.success(car);
    }
    /**
     * @Description: 更新车辆信息
     * @Param: [car]
     * @return: com.weayer.dto.ResponseResult
     **/
    public ResponseResult updateCar(Car car){
        LocalDateTime now = LocalDateTime.now();
        car.setGmtModified(now);
        carMapper.updateById(car);
        return ResponseResult.success("");
    }
    /**
     * @Description: 根据id查询车辆信息
     * @Param: [carId]
     * @return: com.weayer.dto.ResponseResult<com.weayer.dto.Car>
     **/
    public ResponseResult<Car> getCarById(Long carId){
        Map<String, Object> map = new HashMap<>();
        map.put("id", carId);
        List<Car> cars = carMapper.selectByMap(map);
        return ResponseResult.success(cars.get(0));
    }
}
